<template>

	<u-popup :show="show" mode="center" closeable @close="show=false">



		<image v-if="showBtn" :src="imgSrc" style="width: 600rpx;" mode="widthFix"></image>
		<canvas :style="{width:canvasW+'px',height:canvasH+'px'}" v-if="!showBtn" canvas-id="myCanvas-share"
			id="myCanvas-share"></canvas>
		<button type="primary" v-if="showBtn"
			style="width: 200px; line-height:unset; margin:5px auto; font-size:14px;padding: 10px;"
			@click="save">保存到相册</button>

	</u-popup>

</template>

<script>
	import Utils from '@/common/Utils.js'
	export default {
		name: "share-image",
		data() {
			return {
				canvasId: "canvasId",
				codeImg: null,

				canvasW: 300,
				canvasH: 400,

				show: false,

				imageTempPath: "",
				showBtn: false,
				coverImgUrl: "",
				userInfo: {},
				bgImgUrl: "",
				HeadImageUrl: "",
				ownerImgUrl: "",
				goods: {},
				imgSrc: ""
			};
		},
		methods: {

			showPopup(userInfo, goods) {
				this.show = true;
				let _that = this;
				this.userInfo = userInfo;
				this.goods = goods;
				this.showBtn = false;
				this.imgSrc = "";
				console.log()
				this.$nextTick(() => {
					wx.downloadFile({
						url: goods.meta.imageUrl,
						success(uRes) {
							_that.bgImgUrl = uRes.tempFilePath;
							_that.getBarcode(userInfo);
						}
					})

				})


			},


			getBarcode(userInfo, goods) {
				uni.showLoading({
					title: '生成二维码中...',
					mask: false
				});
				let _that = this;
				let url = `${this.$Utils.ApiUrl}/qrcode/requests`;
				let userToken = this.$store.state.userToken;
				console.log(userInfo)
				uni.request({
					url,
					method: 'POST',
					header: {
						Authorization: `Bearer ${userToken}`
					},
					responseType: "arraybuffer",
					data: {
						scene: `${this.goods.id}&${this.userInfo.user.inviteCode}`,
						width: 320,
						page: "pages-publics/GoodsDetails/GoodsDetails",
						envVersion: this.$api.env_version,

					},
					success(res) {
						console.log(res)
						_that.codeImg = res.data;
						//console.log(_that.codeImg)
						const fileName = wx.env.USER_DATA_PATH + '/share_img.png'
						let markdata = 'data:image/jpeg;base64,' + uni.arrayBufferToBase64(res.data)

						const buffer = wx.base64ToArrayBuffer(markdata.replace('data:image/jpeg;base64,',
							''));
						console.log(markdata)
						const fsm = wx.getFileSystemManager();
						fsm.writeFileSync(fileName, buffer, 'binary')

						_that.createShare(fileName);
						console.log(fileName)
						//ctx.drawImage(_that.codeImg, 210, 240, 80, 80) // drawImage(图片路径,x,y,绘制图像的宽度，绘制图像的高度)


					}
				})
			},

			drawCircleImage(ctx, img, x, y, radius) {
				ctx.save();
				ctx.beginPath(); //开始绘制
				let size = 2 * radius;
				ctx.arc(x, y, radius, 0, 2 * Math.PI);
				ctx.clip();
				ctx.drawImage(img, x - radius, y - radius, size, size);
				ctx.restore()

				ctx.closePath()
			},
			//字符换行
			wrapText(context, text, x, y, maxWidth, lineHeight) {
				if (!text) {
					return '暂无'
				}
				if (typeof text != 'string' || typeof x != 'number' || typeof y != 'number') {
					return;
				}
				// 字符分隔为数组
				var arrText = text.split('');
				var line = '';
				let len = 70;
				let tmplen = 70;
				if (arrText.length < len) {
					len = arrText.length;
				}

				for (var n = 0; n < len; n++) {
					var testLine = line + arrText[n];
					var metrics = context.measureText(testLine);
					var testWidth = metrics.width;
					if (testWidth > maxWidth && n > 0) {
						context.fillText(line, x, y);
						line = arrText[n];
						y += lineHeight;
					} else {
						line = testLine;
					}
				}
				context.fillText(line + (arrText.length >= tmplen ? ' ...' : ''), x, y);
			},
			async createShare(fileName) {
				uni.showLoading({
					title: '生成图片中...',
					mask: false
				});
				var that = this;

				let coverImage = await this.getImageInfo(this.goods.meta.imageUrl);
				console.log("coverImage==", coverImage)
				this.canvasW = 600; // 画布宽度
				this.canvasH = 900; // 画布高度 = 主图高度+二维码高度 + 文字图片的间距（大概50）
				var ctx = wx.createCanvasContext('myCanvas-share', this);
				// 填充背景色，白色
				ctx.setFillStyle('#fff'); // 默认白色
				ctx.fillRect(0, 0, this.canvasW, this.canvasH) // fillRect(x,y,宽度，高度)
				ctx.drawImage(this.bgImgUrl, 0, 0, 600, 600);



				ctx.closePath()
				ctx.save();
				ctx.beginPath()
				ctx.setFillStyle('#fff'); // 默认白色
				//ctx.fillRect(0, 200, this.canvasW, 400) // fillRect(x,y,宽度，高度)
				ctx.setFontSize(36);
				ctx.setFillStyle('#ff0101');
				ctx.fillText("￥" + this.goods.price.toFixed(2), 10, 685);
				let w = ctx.measureText(this.goods.price.toFixed(2))
				ctx.setFontSize(24);
				console.log("w=", w)

				let price = this.goods.meta && this.goods.meta.originalPrice && this.goods.meta.originalPrice >
					0 && this.goods
					.meta.originalPrice != this.goods.price ? "￥" + this.goods.meta.originalPrice.toFixed(2) : "";
				ctx.setFillStyle('#111111');
				ctx.fillText(price, w.width + 50, 685);
				if (price) {
					this.drawStrikethroughText(ctx, price, w.width + 50, 675, 2)
				}

				ctx.setFontSize(26);
				this.wrapText(ctx, this.goods.name, 10, 740, 390, 35)


				// const base64 =wx.arrayBufferToBase64(this.codeImg)
				// console.log(base64)
				this.drawCircleImage(ctx, fileName, 490, 710, 70)
				//ctx.drawImage(fileName, 90, 240, 120, 120) // drawImage(图片路径,x,y,绘制图像的宽度，绘制图像的高度)
				ctx.setFontSize(16);
				ctx.fillText("良品至信.至生活", 430, 800);
			    ctx.fillText("一个“工厂直供”的健康平台", 395, 830);


				setTimeout(() => {
					ctx.draw(true, () => {

						uni.hideLoading()
						wx.canvasToTempFilePath({
							canvasId: "myCanvas-share",
							success: function(res) {
								// 获得图片临时路径
								console.log(res)
								that.imageTempPath = res
									.tempFilePath;
								that.imgSrc = that.imageTempPath;
								that.showBtn = true;

								console.log(res.tempFilePath)
							}
						}, this)

					})
				}, 50)
			},
			drawStrikethroughText(context, text, x, y, strikethroughWidth) {
				context.beginPath();
				context.moveTo(x, y);
				context.lineTo(x + context.measureText(text).width, y);
				context.lineWidth = strikethroughWidth; // 删除线的宽度
				context.stroke();
				context.closePath();
			},
			roundRect(ctx, x, y, w, h, r) {
				ctx.save()
				ctx.beginPath()
				// 左上弧线
				ctx.arc(x + r, y + r, r, 1 * Math.PI, 1.5 * Math.PI)
				// 左直线
				ctx.moveTo(x, y + r)
				ctx.lineTo(x, y + h - r)
				// 左下弧线
				ctx.arc(x + r, y + h - r, r, 0.5 * Math.PI, 1 * Math.PI)
				// 下直线
				ctx.lineTo(x + r, y + h)
				ctx.lineTo(x + w - r, y + h)
				// 右下弧线
				ctx.arc(x + w - r, y + h - r, r, 0 * Math.PI, 0.5 * Math.PI)
				// 右直线
				ctx.lineTo(x + w, y + h - r)
				ctx.lineTo(x + w, y + r)
				// 右上弧线
				ctx.arc(x + w - r, y + r, r, 1.5 * Math.PI, 2 * Math.PI)
				// 上直线
				ctx.lineTo(x + w - r, y)
				ctx.lineTo(x + r, y)
				ctx.setStrokeStyle("#ff7300");


				ctx.fill()
			},
			save() {
				var that = this;
				wx.saveImageToPhotosAlbum({
					filePath: this.imageTempPath,
					success(res) {
						wx.showModal({
							content: '图片已保存到相册，赶紧晒一下吧~',
							showCancel: false,
							confirmText: '好的',
							confirmColor: '#333',
							success: function(res) {
								if (res.confirm) {
									console.log('用户点击确定');

								}
								that.show = false;
							},
							fail: function(res) {
								console.log(res)
							}
						})
					}
				});

			},
			getImageInfo(image) {
				return new Promise((req, rej) => {
					uni.getImageInfo({
						src: image,
						success: function(res) {
							req(res)
						},
					});
				})
			},
			// 获取设备信息
			getSystemInfo() {
				return new Promise((req, rej) => {
					uni.getSystemInfo({
						success: function(res) {
							req(res)
						}
					});
				})
			},
		}
	}
</script>

<style>

</style>